package com.wash.shoes.util;

import cn.hutool.core.util.StrUtil;
import lombok.Data;

/**
 * @author lijianguo
 * @Date 2024/7/13 14:42
 * code对应的表信息
 **/
@Data
public class TableCode {
    // 表名字
    String tableName;
    // 字段
    String tableField;
    // 前缀
    String prefix;
    // 查询的sql
    String sql;
    // 长度
    Integer codeLength;
    // 添加的数字
    Integer incNum = 1;

    public String getSqlStr() {
        if (StrUtil.isEmpty(sql)) {
            StringBuilder sb = new StringBuilder();
            sb.append(" SELECT");
            sb.append(" length(").append(tableField).append(") as length,");
            sb.append(" CAST(SUBSTRING(");
            sb.append(tableField);
            sb.append(",");
            if (StrUtil.isEmpty(prefix)) {
                sb.append(1);
            } else {
                sb.append(prefix.length());
            }
            sb.append(" ) AS BIGINT) AS maxCode FROM ").append(tableName);
            sb.append("  ORDER BY maxCode DESC LIMIT 1");
            return sb.toString();
        } else {
            return sql;
        }
    }

    // 下一个code
    public String getNextCode(Long code, Integer length) {
        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        int cl = length - prefix.length();
        code += incNum;
        sb.append(String.format("%0" + cl + "d", code));
        return sb.toString();
    }
}
